//
// Created by WINDOWS on 2025/6/12.
//

#ifndef FILESPACEMONITOR_DIRECTORYMONITOR_H
#define FILESPACEMONITOR_DIRECTORYMONITOR_H

#include <filesystem>
#include <atomic>
#include <thread>
#include <mutex>
#include <map>
#include <chrono>
#include <functional>
#include <system_error>

namespace fs = std::filesystem;

class DirectorySpaceMonitor {
public:
    DirectorySpaceMonitor(fs::path dir_path,
                               std::chrono::seconds interval = std::chrono::seconds(1))
        : dir_path_(std::move(dir_path)),
          scan_interval_(interval),
          running_(false),
          total_size_(0) {

    if (!fs::exists(dir_path_) || !fs::is_directory(dir_path_)) {
        throw std::runtime_error("Invalid directory path");
    }
}

    ~DirectorySpaceMonitor();
    void start();
    void stop();
    uintmax_t get_total_size() const;

    void set_update_callback(std::function<void(uintmax_t)> callback);

private:
    void initial_scan();
    void monitor_loop();
    void scan_changes();
    // 成员变量
    fs::path dir_path_;
    std::chrono::seconds scan_interval_;
    std::atomic<bool> running_;
    std::atomic<uintmax_t> total_size_;

    std::thread monitor_thread_;
    std::map<std::string, uintmax_t> file_cache_;  // 文件路径->大小
    std::mutex cache_mutex_;

    std::function<void(uintmax_t)> update_callback_;
    std::mutex callback_mutex_;
};

#endif //FILESPACEMONITOR_DIRECTORYMONITOR_H
